from django.shortcuts import render
from django.contrib.auth.views import logout
from django.http import HttpResponseRedirect
from django.core.urlresolvers import reverse
from django.contrib.auth.forms import UserCreationForm
from django.contrib.auth.models import User
 
#自带的用户认证相关函数
from django.contrib.auth import login,logout,authenticate


# Create your views here.

def logout_view(request):
    logout(request)
    return HttpResponseRedirect(reverse("learing_logs:index")) #重定向需要导入转换函数 把视图名称转换成url

def register(request):
    if request.method != "POST":
        form = UserCreationForm()
    else:
        form = UserCreationForm(request.POST)
        if form.is_valid():
            new_user = form.save()
            #自动登录刚创建的账号
            authen_user = authenticate(username=new_user.username,password=request.POST['password1']) #认证该用户
            login(request,authen_user)
            return HttpResponseRedirect(reverse('learing_logs:index'))
    #form.labels['username'] = '用户名'
    form.fields['password2'].help_text = "请再次确认密码"
    form.fields['username'].label = '用户名' #django.contrib.auth.forms.UsernameField
    form.fields['password1'].label = '密码' #django.forms.fields.CharField
    form.fields['password2'].label = '确认密码' #django.forms.fields.CharField
    context = {'form':form}
    return render(request,'users/register.html',context=context)

def user_inf(request,user_id):
    cur_user = User.objects.get(id=user_id)
    context = {"cur_user":cur_user}
    return render(request,'users/userInf.html',context)